import React, { useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Send, Settings, Loader2 } from 'lucide-react';
import { AppProviders } from './contexts/AppProviders';
import { useConfig } from './contexts/ConfigContext';
import { useMCP } from './contexts/MCPContext';
import { useChat } from './contexts/ChatContext';
import { useLangGraphChatUI } from './hooks/useLangGraphChatUI';
import type { AnswerStatus } from './lib/langgraph-chat-ui';
import { ActionGroup } from './components/ActionGroup';
import { MessageBubble } from './components/MessageBubble';
import { AnswerCard } from './components/AnswerCard';
import './styles.css';

function LangGraphAppContent() {
  const { state: configState, setApiKey, setModelOverride, saveToStorage, loadFromStorage } = useConfig();
  const { state: mcpState } = useMCP();
  const { state: chatState, setInputValue, addMessage, setStatus } = useChat();
  const { 
    messages,
    answers,
    isLoading, 
    isConfigured, 
    hasMCPEnabled, 
    status: workflowStatus,
    sendMessage, 
    setApiKey: setLangGraphApiKey, 
    setModelOverride: setLangGraphModelOverride, 
    saveToStorage: saveLangGraphConfig, 
    loadFromStorage: loadLangGraphConfig,
    resetWorkflowUI,
    toggleActionCollapse,
    toggleActionSection
  } = useLangGraphChatUI();
  const [isMCPDialogOpen, setIsMCPDialogOpen] = React.useState(false);
  const agentToolList = React.useMemo(() => {
    return Array.from(mcpState.agentsStatus.entries()).map(([agentId, status]) => ({
      agentId,
      label: status.label || agentId,
      enabled: status.enabled,
      tools: status.tools ?? [],
      toolsCount: status.toolsCount ?? (status.tools?.length ?? 0)
    }));
  }, [mcpState.agentsStatus]);
  const enabledAgentsCount = React.useMemo(() => agentToolList.filter(item => item.enabled).length, [agentToolList]);
  const totalAgentsCount = agentToolList.length;
  const totalToolsCount = React.useMemo(() => {
    const uniqueTools = new Set<string>();
    agentToolList.forEach((item) => {
      item.tools.forEach(tool => uniqueTools.add(tool));
    });
    return uniqueTools.size;
  }, [agentToolList]);

  // 同步配置状态
  useEffect(() => {
    if (configState.apiKey) {
      setLangGraphApiKey(configState.apiKey);
    }
    if (configState.modelOverride) {
      setLangGraphModelOverride(configState.modelOverride);
    }
  }, [configState.apiKey, configState.modelOverride]);

  // 加载用户配置
  useEffect(() => {
    loadFromStorage();
    loadLangGraphConfig();
  }, []);

  // 添加欢迎消息
  useEffect(() => {
    if (messages.length === 0) {
      addMessage({
        type: 'bot',
        content: '👋 你好！先在上方配置 OpenRouter API Key（LangGraph 版本）',
        timestamp: new Date().toLocaleTimeString(),
        markdown: true
      });
    }
  }, [messages.length]);

  const handleSendMessage = async () => {
    if (!chatState.inputValue.trim()) return;

    try {
      await sendMessage(chatState.inputValue);
      setInputValue('');
    } catch (error) {
      console.error('发送消息失败:', error);
    }
  };

  const handleSaveConfig = async () => {
    await saveToStorage();
    await saveLangGraphConfig();
    setStatus('配置已保存');
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <div className="min-h-screen bg-gray-900 text-white">
      {/* 配置区域 */}
      <div className="border-b border-gray-700 p-4">
        <div className="flex items-center gap-4 mb-4">
          <h1 className="text-xl font-bold">PG-ZDM 智能购物助手 (LangGraph)</h1>
          <div className="text-sm text-gray-400 flex items-center gap-2">
            <span>{workflowStatus || chatState.status}</span>
            {isLoading && (
              <Loader2 className="w-4 h-4 animate-spin text-blue-300" />
            )}
          </div>
          {hasMCPEnabled && (
            <Dialog open={isMCPDialogOpen} onOpenChange={setIsMCPDialogOpen}>
              <DialogTrigger asChild>
                <button
                  type="button"
                  className="text-sm text-green-400 hover:text-green-200 underline-offset-2 hover:underline"
                >
                  MCP: {enabledAgentsCount}/{totalAgentsCount} ({totalToolsCount} 工具)
                </button>
              </DialogTrigger>
              <DialogContent className="max-w-xl bg-gray-900 text-white border border-gray-700">
                <DialogHeader>
                  <DialogTitle>可用 MCP 工具</DialogTitle>
                </DialogHeader>
                {agentToolList.length === 0 ? (
                  <p className="text-sm text-gray-400">暂未加载到任何 MCP 工具。</p>
                ) : (
                  <div className="space-y-4 max-h-80 overflow-y-auto pr-1">
                    {agentToolList.map((item) => (
                      <div key={item.agentId} className="border border-gray-800 rounded-lg p-3 bg-gray-900/60">
                        <div className="flex items-center justify-between">
                          <span className="font-semibold text-white">{item.label}</span>
                          <span className="text-xs text-gray-400">{item.toolsCount} 个工具</span>
                        </div>
                        {item.tools.length === 0 ? (
                          <p className="text-xs text-gray-500 mt-2">暂无可用工具</p>
                        ) : (
                          <ul className="mt-2 space-y-1 text-sm text-gray-200">
                            {item.tools.map((tool) => (
                              <li key={tool} className="bg-gray-800/70 px-3 py-1 rounded border border-gray-700/60">
                                {tool}
                              </li>
                            ))}
                          </ul>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </DialogContent>
            </Dialog>
          )}
        </div>
        
        <div className="flex gap-4">
          <Input
            type="password"
            placeholder="OpenRouter API Key"
            value={configState.apiKey}
            onChange={(e) => setApiKey(e.target.value)}
            className="flex-1 bg-gray-800 border-gray-600 text-white placeholder:text-gray-400 focus:border-blue-500 focus:ring-blue-500"
          />
          <Input
            placeholder="模型覆盖 (可选)"
            value={configState.modelOverride}
            onChange={(e) => setModelOverride(e.target.value)}
            className="flex-1 bg-gray-800 border-gray-600 text-white placeholder:text-gray-400 focus:border-blue-500 focus:ring-blue-500"
          />
          <Button onClick={handleSaveConfig} className="bg-blue-600 hover:bg-blue-700 text-white border-blue-500">
            <Settings className="w-4 h-4 mr-2" />
            保存配置
          </Button>
        </div>
      </div>

      {/* 聊天区域 */}
      <div className="flex-1 overflow-hidden">
        <div className="h-full overflow-y-auto p-4 space-y-4">
          {messages.map((message, index) => (
            <div key={index}>
              {message.type === 'action' ? (
                <ActionGroup
                  action={message.action}
                  status={message.status as string}
                  timestamp={message.timestamp}
                  content={message.content}
                  onToggleCollapse={() => {
                    if (!message.action?.action_id) return;
                    toggleActionCollapse(message.action.action_id);
                  }}
                  isCollapsed={message.isCollapsed || false}
                  sections={message.sections}
                  onToggleSection={(sectionId) => {
                    if (!message.action?.action_id) return;
                    toggleActionSection(message.action.action_id, sectionId);
                  }}
                />
              ) : (
                <MessageBubble
                  content={message.content}
                  type={message.type}
                  timestamp={message.timestamp}
                  markdown={message.markdown}
                />
              )}
            </div>
          ))}

          {answers.map((card, index) => (
            <div key={`answer-${index}`}>
              <AnswerCard
                content={card.content}
                status={(card.status as AnswerStatus) || 'loading'}
                timestamp={card.timestamp}
              />
            </div>
          ))}
        </div>
      </div>

      {/* 输入区域 */}
      <div className="border-t border-gray-700 p-4">
        <div className="flex gap-4">
          <Input
            value={chatState.inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入你的问题..."
            disabled={isLoading || !isConfigured}
            className="flex-1 bg-gray-800 border-gray-600 text-white placeholder:text-gray-400 focus:border-blue-500 focus:ring-blue-500 disabled:bg-gray-700 disabled:text-gray-500"
          />
          <Button 
            onClick={handleSendMessage}
            disabled={!chatState.inputValue.trim() || isLoading || !isConfigured}
            className="bg-blue-600 hover:bg-blue-700 text-white border-blue-500 disabled:bg-gray-600 disabled:text-gray-400"
          >
            <Send className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  );
}

export default function LangGraphApp() {
  return (
    <AppProviders>
      <LangGraphAppContent />
    </AppProviders>
  );
}
